package work.servlet.exam;

import staticClass.cookieMa.CookieManage;
import staticClass.score.SubmitExam;
import tool.classes.exam.Exam;
import tool.property.exam.ExamProperty;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet(name = "ServletExam", value = "/exam")
public class ServletExam extends HttpServlet {
    //显示试题
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int t = Integer.parseInt(request.getParameter("t"));
        if (request.getSession().getAttribute("exams") == null) {
            ArrayList<ExamProperty> exam = new Exam().getChoiceExam(t);
            request.setAttribute("t", t);
            request.getSession().setAttribute("exams", exam);
        }
        request.getRequestDispatcher("/exam/examWrite.jsp").forward(request, response);

    }

    //提交答案
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int t = Integer.parseInt(request.getParameter("t"));
        response.setContentType("text/html;charset=utf-8");

        ArrayList<ExamProperty> exams = (ArrayList<ExamProperty>) request.getSession().getAttribute("exams");

        request.getSession().removeAttribute("exams");
        Enumeration<String> paras = request.getParameterNames();
        int i = 0;

        HashMap<ExamProperty, String> showMap = new HashMap<>();

        for (ExamProperty exam :
                exams) {
            showMap.put(exam, "未作答");
        }

        Set<ExamProperty> exs = showMap.keySet();


        while (paras.hasMoreElements()) {
            String pid = paras.nextElement();
            if (pid.equals("t")) {
                continue;
            }
            String ans = request.getParameter(pid);

            for (ExamProperty ex :
                    exs) {
                if (ex.getId() == Integer.parseInt(pid) && ex.getAnswer().equals(ans)) {
                    showMap.remove(ex);
                    break;
                }

                if (ex.getId() == Integer.parseInt(pid) && !ex.getAnswer().equals(ans)) {
                    showMap.put(ex, ans);
                    break;
                }
            }
        }

        Cookie[] cookies = request.getCookies();
        Cookie email = CookieManage.getCookie(cookies, "email");

        SubmitExam.UpdateScore(email.getValue(), t, i);

        request.setAttribute("score", i);
        request.setAttribute("ans", showMap);

        request.getRequestDispatcher("/exam/examShowAns.jsp").forward(request, response);

    }
}
